Skip to main content

Simplify your SPFx imports

·2 mins

The thought

Having worked in SPFx for long enough, I’m sure you’ve seen imports like this:

import { IMyInterface } from '../../../../../../common/models/IMyInterface';

And thought, “there must be a better way!”, looking at library imports, you’ll see that they’re much cleaner:

import { SPFI } from "@pnp/sp";

Well, there’s a way to turn your imports into something similar, and it’s not that hard!

// Let's turn this:
import { IMyInterface } from '../../../../../../common/models/IMyInterface';
// into this:
import { IMyInterface } from '@Models/IMyInterface';

The solution

It’s actually quite simple, we’ll only need to update two files (three if you’re using fast-serve).

gulpfile.js

Firstly we need to update out webpack file, now normally this would be done in the webpack.config.js file, however SPFx does webpack a bit different, instead they allow us to modify parts of the webpack config during the build process, this is done in the gulpfile.js file.

Add the followind lines of code, beware of the path, we’re replacing src with lib as that’s where the files will be after the build process.

gulpfile.js

const path = require('path');

...

build.configureWebpack.mergeConfig({
  additionalConfiguration: (generatedConfiguration) => {
    if (!generatedConfiguration.resolve.alias)
      generatedConfiguration.resolve.alias = {};

    generatedConfiguration.resolve.alias['@Models'] = path.resolve(__dirname, './lib/@common/models/')

    return generatedConfiguration;
  }
});

tsconfig.json

Next we’re going to update the tsconfig.json file, this is where we’ll tell TypeScript that we’ve updated the paths, and where to find them, so that we don’t get errors while coding.

Note that we’ll be using the src part here, and setting the base url to ..

tsconfig.json

...
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@Models/*": [
        "src/@common/models/*"
      ]
    },
...

webpack.extend.js (Fast Serve)

Lastly, if you’re using fast-serve, you’ll need to update the webpack.extend.js file in your fast-serve folder, and add the following lines:

webpack.extend.js

const path = require('path');

...

const webpackConfig = {
  resolve: {
    alias: {
      '@Models': path.resolve(__dirname, '..', 'src/@common/models/')
    }
  }
}

Now common for all of these things we just did is that you can add as many as you want! - I sometimes find myself ending up with the following list of aliases:

  • @Common
  • @Models
  • @Enums
  • @Utils
  • @Hooks
  • @Contexts

And that’s just for inspiration, you can keep going! - please let me know what you come up with!

TL;DR

You can drastically improve the readability of your SPFx imports by setting up what are called aliases, and thereby shortening your import statements, and “obfuscating” away the folder structure.